import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { hasPermissionForPath } from '@/router/dynamic'

// 基础路由（无需权限）
const baseRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '登录',
      hidden: true
    }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/404.vue'),
    meta: {
      title: '页面不存在',
      hidden: true
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/layout/index.vue'),
    children: [
      {
        path: '',
        name: 'DashboardHome',
        component: () => import('@/views/dashboard/index.vue'),
        meta: {
          title: '仪表盘',
          icon: 'DashboardOutlined'
        }
      }
    ]
  },
  {
    path: '/',
    redirect: '/dashboard'
  },
  // 404路由必须放在最后，作为兜底
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...baseRoutes]
})

// 简化的全局前置守卫
router.beforeEach(async (to, from, next) => {
  
  const authStore = useAuthStore()
  const token = authStore.token
  
  // 白名单路由（无需登录）
  const whiteList = ['/login', '/404']

  if (!token) {
    // 未登录用户
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
    return
  }

  // 已登录用户
  if (to.path === '/login') {
    next('/dashboard')
    return
  }

  // 对于白名单路由，直接通过
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  // 对于dashboard，直接通过
  if (to.path === '/dashboard') {
    next()
    return
  }

  // 检查是否有该路径的权限（动态路由）
  if (!hasPermissionForPath(to.path)) {
    next('/404')
    return
  }

  next()
})

export default router
